package cn.bluech.lib.ui.widget.paging;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.AbsListView;
import android.widget.GridView;

/**
 * Description:
 * Create by Codeant on 2018/10/29.
 */
public class PagingGridView extends GridView {
    private IOnLoad loader;
    private boolean nonMoreData;

    public PagingGridView(Context context) {
        this(context,null);
    }

    public PagingGridView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public PagingGridView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        setOnScrollListener(onScrollListener);
    }

    public void setLoader(IOnLoad loader) {
        this.loader = loader;
    }

    public void reLoad(){
        nonMoreData = false;
    }

    private OnScrollListener onScrollListener = new OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if(scrollState == OnScrollListener.SCROLL_STATE_IDLE) { // 滚动停止时
                if(nonMoreData)
                    return;
                int pos = view.getLastVisiblePosition();
                if((pos+1==getCount())||(getCount()==0)){
                    if(null!=loader)
                        nonMoreData = loader.onLoad(pos+1);
                }
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        }
    };


    public interface IOnLoad {
        /**
         * 加载数据接口，如果是异步加载可能会重复调用(还没加载结束会有重入的概率)
         * @param loadPos 要加载的起始位置
         * @return 是否已经全部加载完成，返回true就不再继续加载
         */
        boolean onLoad(int loadPos);
    }
}
